package m202405.d14;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/14 14:22
 */
public class Q34 {

    public static void main(String[] args) {
        Q34 q34 = new Q34();
        q34.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8);
    }

    public int[] searchRange(int[] nums, int target) {
        int[] res = new int[]{-1, -1};
        if (nums == null || nums.length == 0) {
            return res;
        }
        int current = find(nums, 0, nums.length, target);
        if (current == -1) {
            return res;
        }
        //左边
        int left = current;
        while (left != 0 && nums[left - 1] == target) {
            left = find(nums, 0, left, target);
        }
        res[0] = left;
        //右边
        int right = current;
        while (right != nums.length - 1 && nums[right + 1] == target) {
            right = find(nums, right + 1, nums.length, target);
        }
        res[1] = right;
        return res;
    }

    private int find(int[] nums, int start, int end, int target) {
        if (start + 1 == end) {
            return nums[start] == target ? start : -1;
        }
        int mid = (start + end) / 2;
        if (target < nums[mid]) {
            return find(nums, start, mid, target);
        } else if (target > nums[mid]) {
            return find(nums, mid, end, target);
        } else {
            return mid;
        }
    }
}
